package com.learn.demo.netty.codec;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.CharsetUtil;

import java.nio.charset.StandardCharsets;
import java.util.Random;

/**
 * 自定义客户端消息处理handler，需要继承HandlerAdapter
 */
public class NettyClientHandlerDemo extends ChannelInboundHandlerAdapter {

    /**
     * 通道就绪触发的事件
     * @param ctx
     * @throws Exception
     */
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("ChannelHandlerContext is " + ctx);
        int random = new Random().nextInt(3);
        MyDataInfo.MyMessage myMessage = null;
        if(0 == random){
            myMessage = MyDataInfo.MyMessage.newBuilder().setDataType(MyDataInfo.MyMessage.DataType.StudentType).setStudent(MyDataInfo.Student.newBuilder().setId(1).setName("测试").build()).build();
        }else {
            myMessage = MyDataInfo.MyMessage.newBuilder().setDataType(MyDataInfo.MyMessage.DataType.WorkerType).setWorker(MyDataInfo.Worker.newBuilder().setAge(18).setName("张三")).build();
        }
        //给服务器发送消息
        ctx.writeAndFlush(myMessage);
    }

    /**
     * 通道读取事件
     * @param ctx
     * @param msg
     */
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) {
        //netty包装的消息缓冲类，效率比NIO的ByteBuffer高
        ByteBuf byteBuf = (ByteBuf) msg;
        System.out.println("the msg from server is " + byteBuf.toString(CharsetUtil.UTF_8));
        System.out.println("the address of server is " + ctx.channel().remoteAddress());
    }

    /**
     * 异常处理
     * @param ctx
     * @param cause
     */
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        cause.printStackTrace();
        ctx.close();
    }
}
